import 'package:flutter/material.dart';
import 'bill.dart';
import 'next_page.dart';
import 'login_register_page.dart';
import 'expense.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final List<Bill> bills = []; // 存储账目列表

  void addBill(Bill bill) {
    setState(() {
      bills.add(bill);
    });
  }

  void _handleLogout() {
    Navigator.pushAndRemoveUntil(
      context,
      MaterialPageRoute(builder: (context) => const LoginRegisterPage()),
      (Route<dynamic> route) => false,
    );
  }

  // 按日期分组账单
  List<Widget> _buildBillGroups() {
    Map<String, List<Bill>> groups = {};
    for (Bill bill in bills) {
      final date = bill.getFormattedDate();
      if (!groups.containsKey(date)) {
        groups[date] = [];
      }
      groups[date]?.add(bill);
    }

    // 将分组后的账单转换为Widget列表
    return groups.entries.map<Widget>((entry) {
      final date = entry.key;
      final billsForDate = entry.value;
      DateTime dateTime = DateTime.parse(date);
      String weekday = getWeekday(dateTime);

      List<Widget> billWidgets = [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Text(
                date,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 18,
                ),
              ),
              Text(" $weekday", style: TextStyle(fontSize: 16)),
            ],
          ),
        ),
      ];

      for (Bill bill in billsForDate) {
        billWidgets.add(
          Padding(
            padding:
                const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(bill.note), // 显示备注
                Row(
                  children: [
                    Text(bill.description == '收入' ? '+' : '-', // 根据收入或支出显示符号
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        )),
                    Text(bill.amount), // 显示金额
                  ],
                ),
              ],
            ),
          ),
        );
        billWidgets.add(SizedBox(
            height: 1, child: Divider(indent: 16, endIndent: 16))); // 添加分割线
      }

      return Column(children: billWidgets);
    }).toList();
  }

  // 获取星期几
  String getWeekday(DateTime dateTime) {
    final daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    return daysOfWeek[dateTime.weekday - 1];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text("Account"),
        actions: [
          PopupMenuButton(
            itemBuilder: (BuildContext context) {
              return [
                PopupMenuItem(
                  child: Text('Logout'),
                  value: 1,
                  onTap: () {
                    _handleLogout();
                  },
                ),
              ];
            },
          ),
        ],
      ),
      body: Stack(
        children: [
          Expanded(
            child: ListView(
              children: _buildBillGroups(),
            ),
          ),
          Positioned(
            bottom: 16.0,
            left: 0,
            right: 0,
            child: Container(
              height: 160,
              width: MediaQuery.of(context).size.width - 32.0,
              decoration: BoxDecoration(
                color: Colors.grey[200],
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 8,
                  )
                ],
              ),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Container(
                            width: 50,
                            height: 50,
                            decoration: BoxDecoration(
                              color: Colors.red.withOpacity(0.7),
                              shape: BoxShape.circle,
                            ),
                            child: Center(
                              child: IconButton(
                                icon: Icon(Icons.assignment,
                                    color: Colors.white, size: 30.0),
                                onPressed: () {},
                              ),
                            ),
                          ),
                          SizedBox(height: 8),
                          Text('明细',
                              style: TextStyle(
                                  fontSize: 12, color: Colors.grey[700])),
                        ],
                      ),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Container(
                            width: 60,
                            height: 60,
                            decoration: BoxDecoration(
                              color: Colors.green.withOpacity(0.7),
                              shape: BoxShape.circle,
                            ),
                            child: Center(
                              child: IconButton(
                                icon: Icon(Icons.add,
                                    color: Colors.white, size: 40.0),
                                onPressed: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) =>
                                          NextPage(addBill: addBill),
                                    ),
                                  );
                                },
                              ),
                            ),
                          ),
                          SizedBox(height: 8),
                          Text('记账',
                              style: TextStyle(
                                  fontSize: 12, color: Colors.grey[700])),
                        ],
                      ),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Container(
                            width: 50,
                            height: 50,
                            decoration: BoxDecoration(
                              color: Colors.blue.withOpacity(0.7),
                              shape: BoxShape.circle,
                            ),
                            child: Center(
                              child: IconButton(
                                icon: Icon(Icons.trending_up,
                                    color: Colors.white, size: 30.0),
                                onPressed: () {
                                  // Navigator.push(
                                  //   context,
                                  //   MaterialPageRoute(
                                  //     builder: (context) =>
                                  //         ExpenseRankingPage(bills: bills),
                                  //   ),
                                  // );
                                },
                              ),
                            ),
                          ),
                          SizedBox(height: 8),
                          Text('图标',
                              style: TextStyle(
                                  fontSize: 12, color: Colors.grey[700])),
                        ],
                      ),
                    ],
                  ),
                  SizedBox(height: 8),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
